package com.example.ktapplication.adapter

import android.annotation.SuppressLint
import android.graphics.Paint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.ktapplication.R
import com.example.ktapplication.bean.Sys
import com.example.ktapplication.databinding.RvSystemItemLayoutBinding

class SystemListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val links by lazy {
        mutableListOf<Sys>()
    }

    var itemCallBack: OnItemClickListener? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.rv_system_item_layout, parent, false)
        return SysViewHolder(view)
    }

    override fun getItemCount(): Int {
        return links.size
    }

    @SuppressLint("NotifyDataSetChanged")
    fun addData(data: MutableList<Sys>) {
        links.clear()
        data.sortBy { it.name }
        links.addAll(data)
        notifyDataSetChanged()
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is SysViewHolder) {
            val sysItem = links[position]
            holder.binding.root.setOnClickListener {
                itemCallBack?.onTitleClick(sysItem)
            }
            holder.binding.txtTitle.apply {
                text = sysItem.name
            }
            holder.binding.linkList.removeAllViews()
            sysItem.children.forEach {
                val sysChild = it

                val tvLink = TextView(holder.binding.txtTitle.context)
                tvLink.text = sysChild.name
                tvLink.paintFlags = tvLink.paintFlags or Paint.UNDERLINE_TEXT_FLAG

                holder.binding.linkList.apply {
                    addSearchItem(tvLink, sysChild)
                    addItemCallBack { item ->
                        val link = item as Sys.SysChild
                        itemCallBack?.onLinkClick(sysItem, link)
                    }
                }
            }
        }
    }

    inner class SysViewHolder(item: View) : RecyclerView.ViewHolder(item) {
        val binding by lazy {
            RvSystemItemLayoutBinding.bind(item)
        }
    }

    interface OnItemClickListener {
        fun onLinkClick(sys: Sys, sysChild: Sys.SysChild)

        fun onTitleClick(sys: Sys)
    }
}